#include <stdio.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include "mqtt_hal.h"
#include "esp_wifi.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "esp_event.h"
#include "esp_netif.h"
#include "protocol_examples_common.h"
#include "cJSON.h"
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/semphr.h"
#include "freertos/queue.h"

#include "lwip/sockets.h"
#include "lwip/dns.h"
#include "lwip/netdb.h"
#include "wifi_hal.h"
#include "espnow.h"
#include "esp_now_hal.h"

#include "protocol_examples_common.h"
#include "example_common_private.h"

#include "esp_log.h"
#include "mqtt_client.h"

#include "ch423.h"
#include "hlw8032.h"

static const char *TAG = "MQTT_HAL";

static SemaphoreHandle_t xMQTTSemaphore; /* mqtt mutex */

/**
 * @brief log_error_if_nonzero
 *
 * @param message
 * @param error_code
 */
static void log_error_if_nonzero(const char *message, int error_code)
{
    if (error_code != 0)
    {
        ESP_LOGE(TAG, "Last error %s: 0x%x", message, error_code);
    }
}

/**
 * @brief mqtt_handle_relay
 *
 * @param object
 * @param string
 * @param ch423_oc_pin
 */
static void mqtt_handle_relay(const cJSON *const object, const char *const string, ch423_oc_l_enmu ch423_oc_pin)
{
    cJSON *obj_param = cJSON_GetObjectItem(object, string);
    if (obj_param == NULL || !cJSON_IsNumber(obj_param))
    {
        ESP_LOGW(TAG, "no found key[%s]", string);
        cJSON_Delete(obj_param);
    }
    else
    {
        ESP_LOGI(TAG, "[%s]:%d", string, obj_param->valueint);
        ch423_set_oc_level(ch423_oc_pin, obj_param->valueint);
    }
}

/**
 * @brief mqtt_handle_relay
 *
 * @param str_buff
 */
static void mqtt_handle_cjson_data(char *str_buff)
{
    cJSON *root = cJSON_Parse(str_buff);
    if (root == NULL)
    {
        ESP_LOGW(TAG, "cjson root is null.");
    }
    else
    {
        cJSON *params = cJSON_GetObjectItem(root, "params");
        if (params == NULL || !cJSON_IsObject(params))
        {
            ESP_LOGW(TAG, "handle params obj.");
            cJSON_Delete(root);
        }
        else
        {
            /* handle value start */
            mqtt_handle_relay(params, "Living_Light", OC_L_0);
            mqtt_handle_relay(params, "Living_Fan", OC_L_1);
            mqtt_handle_relay(params, "Living_AirCondition", OC_L_2);
            mqtt_handle_relay(params, "Living_TV", OC_L_3);
            mqtt_handle_relay(params, "Living_AirPurifier", OC_L_4);
            mqtt_handle_relay(params, "Bed_Light", OC_L_5);
            mqtt_handle_relay(params, "Bed_Fan", OC_L_6);
            mqtt_handle_relay(params, "Bed_AirCondition", OC_L_7);
            /* handle value end */

            cJSON_Delete(root);
        }
    }
}

/*
 * @brief Event handler registered to receive MQTT events
 *
 *  This function is called by the MQTT client event loop.
 *
 * @param handler_args user data registered to the event.
 * @param base Event base for the handler(always MQTT Base in this example).
 * @param event_id The id for the received event.
 * @param event_data The data for the event, esp_mqtt_event_handle_t.
 */
static void mqtt_event_handler(void *handler_args, esp_event_base_t base, int32_t event_id, void *event_data)
{
    ESP_LOGD(TAG, "Event dispatched from event loop base=%s, event_id=%" PRIi32 "", base, event_id);
    esp_mqtt_event_handle_t event = event_data;
    esp_mqtt_client_handle_t client = event->client;
    int msg_id;
    switch ((esp_mqtt_event_id_t)event_id)
    {
    case MQTT_EVENT_CONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_CONNECTED");
        msg_id = esp_mqtt_client_publish(client, "/topic/qos1", "data_3", 0, 1, 0);
        ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);

        msg_id = esp_mqtt_client_subscribe(client, "/topic/qos0", 0);
        ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

        msg_id = esp_mqtt_client_subscribe(client, "/topic/qos1", 1);
        ESP_LOGI(TAG, "sent subscribe successful, msg_id=%d", msg_id);

        // msg_id = esp_mqtt_client_unsubscribe(client, "/topic/qos1");
        // ESP_LOGI(TAG, "sent unsubscribe successful, msg_id=%d", msg_id);
        break;
    case MQTT_EVENT_DISCONNECTED:
        ESP_LOGI(TAG, "MQTT_EVENT_DISCONNECTED");
        break;

    case MQTT_EVENT_SUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_SUBSCRIBED, msg_id=%d", event->msg_id);
        msg_id = esp_mqtt_client_publish(client, "/topic/qos0", "data", 0, 0, 0);
        ESP_LOGI(TAG, "sent publish successful, msg_id=%d", msg_id);
        break;
    case MQTT_EVENT_UNSUBSCRIBED:
        ESP_LOGI(TAG, "MQTT_EVENT_UNSUBSCRIBED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_PUBLISHED:
        ESP_LOGI(TAG, "MQTT_EVENT_PUBLISHED, msg_id=%d", event->msg_id);
        break;
    case MQTT_EVENT_DATA:
        ESP_LOGI(TAG, "MQTT_EVENT_DATA");
        printf("TOPIC=%.*s\r\n", event->topic_len, event->topic);
        printf("DATA=%.*s\r\n", event->data_len, event->data);
        mqtt_handle_cjson_data(event->data);
        break;
    case MQTT_EVENT_ERROR:
        ESP_LOGI(TAG, "MQTT_EVENT_ERROR");
        if (event->error_handle->error_type == MQTT_ERROR_TYPE_TCP_TRANSPORT)
        {
            log_error_if_nonzero("reported from esp-tls", event->error_handle->esp_tls_last_esp_err);
            log_error_if_nonzero("reported from tls stack", event->error_handle->esp_tls_stack_err);
            log_error_if_nonzero("captured as transport's socket errno", event->error_handle->esp_transport_sock_errno);
            ESP_LOGI(TAG, "Last errno string (%s)", strerror(event->error_handle->esp_transport_sock_errno));
        }
        break;
    default:
        ESP_LOGI(TAG, "Other event id:%d", event->event_id);
        break;
    }
}

void mqtt_wifi_init(void)
{
    ESP_LOGI(TAG, "[APP] Startup..");
    ESP_LOGI(TAG, "[APP] Free memory: %" PRIu32 " bytes", esp_get_free_heap_size());
    ESP_LOGI(TAG, "[APP] IDF version: %s", esp_get_idf_version());

    esp_log_level_set("*", ESP_LOG_INFO);
    esp_log_level_set("mqtt_client", ESP_LOG_VERBOSE);
    esp_log_level_set("MQTT_EXAMPLE", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT_BASE", ESP_LOG_VERBOSE);
    esp_log_level_set("esp-tls", ESP_LOG_VERBOSE);
    esp_log_level_set("TRANSPORT", ESP_LOG_VERBOSE);
    esp_log_level_set("outbox", ESP_LOG_VERBOSE);

    /* plese not retry to run these:< */
    ESP_ERROR_CHECK(nvs_flash_init());
    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    // wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    // ESP_ERROR_CHECK(esp_wifi_init(&cfg));
    // ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
    // ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
    // ESP_ERROR_CHECK(esp_wifi_start());

    /* This helper function configures Wi-Fi or Ethernet, as selected in menuconfig.
     * Read "Establishing Wi-Fi or Ethernet Connection" section in
     * examples/protocols/README.md for more information about this function.
     */
    ESP_ERROR_CHECK(example_connect());
}

void mqtt_task(void *arg)
{
    static uint8_t mqtt_tick = 0;
    static uint8_t io_data = 0;
    /* mqtt mutex create start */
    xMQTTSemaphore = xSemaphoreCreateMutex(); /* create mqtt mutex */
    if (xMQTTSemaphore != NULL)
    {
        ESP_LOGI(TAG, "Creat xMQTTSemaphore successfully");
    }
    else
    {
        /* error handler begin */
        ESP_LOGE(TAG, "Creat xMQTTSemaphore error. err msg->%s,,%s", __FILE__, __func__);
        vSemaphoreDelete(xMQTTSemaphore);
        /* error handler end */
    }
    /* mqtt mutex create end */

    esp_mqtt_client_config_t mqtt_cfg = {
        .broker.address.hostname = BROLER_ADDRESS,           /* broker address */
        .broker.address.port = BROLER_PORT,                  /* broker port -- type is uint32_t */
        .broker.address.transport = MQTT_TRANSPORT_OVER_TCP, /* broker address transport */
        .credentials.client_id = CLIENT_ID,                  /* client id */
        .credentials.username = USER_NAME,                   /* user credentials name */
        .credentials.authentication.password = PASSWARD,     /* user credential passward */
    };

    esp_mqtt_client_handle_t client = esp_mqtt_client_init(&mqtt_cfg);
    /* The last argument may be used to pass data to the event handler, in this example mqtt_event_handler */
    // esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_register_event(client, ESP_EVENT_ANY_ID, mqtt_event_handler, NULL);
    esp_mqtt_client_start(client);

    char publish_data_buff[10];
    char mqtt_publish_data[] = "\
    {\
        \"id\":\
        \"1\",\
        \"version\":\
        \"1.0\",\
        \"params\":\
        {\
            \"RMSVoltage\":220.12,\
            \"RMSCurrent\":2.21,\
            \"ActivePower\":500.21,\
            \"AC_P\":1000.55,\
            \"PowerRatio\":0.98,\
            \"PF_C\":65535,\
            \"One_Pulses\":65536,\
            \"PowerConsumption\":50.2458,\
            \"ElectricalOpen_Num\":8,\
            \"SOP2\":88,\
            \"HeartRate\":95,\
            \"Living_Light\":1,\
            \"Living_Fan\":1,\
            \"Living_AirCondition\":1,\
            \"Living_TV\":1,\
            \"Living_AirPurifier\":1,\
            \"Bed_Light\":1,\
            \"Bed_Fan\":1,\
            \"Bed_AirCondition\":1\
        }\
    }";

    while (1)
    {
        mqtt_tick++;
        /* retry connect wifi start */
        if (wifi_switch_panel().wifi_connect_proc == 1) /* retry connect wifi */
        {
            if (wifi_hal_connect() != ESP_OK)
            {
                ESP_LOGW(TAG, "wifi connect fail. please retry.");
            }
            else
            {
                espnow_config_t espnow_config = ESPNOW_INIT_CONFIG_DEFAULT();
                ESP_ERROR_CHECK(espnow_init(&espnow_config));
            }
            set_wifi_hal_conf_proc(0);
        }
        /* retry connect wifi end */

        /* publish msg to Aliyun start */
        if (mqtt_tick >= 8)
        {
            mqtt_tick = 0;
            if (pdTRUE == xSemaphoreTake(xMQTTSemaphore, portMAX_DELAY))
            {
                if (wifi_panel().authmode != WIFI_AUTH_OPEN) /* check wifi is connect */
                {
                    cJSON *root = cJSON_Parse(mqtt_publish_data);
                    cJSON *params = cJSON_GetObjectItemCaseSensitive(root, "params");

                    /* update mqtt cjson data start */
                    cJSON *params_value = cJSON_GetObjectItemCaseSensitive(params, "RMSVoltage");  /* EFFECTIVE_VOLTAGE */
                    sprintf(publish_data_buff, "%.3f", hlw8032_get_data(EFFECTIVE_VOLTAGE));       /* EFFECTIVE_VOLTAGE */
                    cJSON_SetNumberValue(params_value, atof(publish_data_buff));                   /* EFFECTIVE_VOLTAGE */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "RMSCurrent");         /* EFFECTIVE_CURRENT */
                    sprintf(publish_data_buff, "%.3f", hlw8032_get_data(EFFECTIVE_CURRENT));       /* EFFECTIVE_CURRENT */
                    cJSON_SetNumberValue(params_value, atof(publish_data_buff));                   /* EFFECTIVE_CURRENT */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "ActivePower");        /* ACTIVE_POWER */
                    sprintf(publish_data_buff, "%.3f", hlw8032_get_data(ACTIVE_POWER));            /* ACTIVE_POWER */
                    cJSON_SetNumberValue(params_value, atof(publish_data_buff));                   /* ACTIVE_POWER */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "AC_P");               /* APPARENT_POWER */
                    sprintf(publish_data_buff, "%.3f", hlw8032_get_data(APPARENT_POWER));          /* APPARENT_POWER */
                    cJSON_SetNumberValue(params_value, atof(publish_data_buff));                   /* APPARENT_POWER */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "PowerRatio");         /* FACTOR */
                    sprintf(publish_data_buff, "%.3f", hlw8032_get_data(FACTOR));                  /* FACTOR */
                    cJSON_SetNumberValue(params_value, atof(publish_data_buff));                   /* FACTOR */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "PF_C");               /* PF_COUNT */
                    cJSON_SetNumberValue(params_value, hlw8032_get_data(PF_COUNT));                /* PF_COUNT */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "One_Pulses");         /* ONE_PULSES */
                    cJSON_SetNumberValue(params_value, hlw8032_get_data(ONE_PULSES));              /* ONE_PULSES */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "PowerConsumption");   /* EFFECTIVE_CALCULATION */
                    cJSON_SetNumberValue(params_value, hlw8032_get_data(EFFECTIVE_CALCULATION));   /* EFFECTIVE_CALCULATION */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "ElectricalOpen_Num"); /* ElectricalOpen_Num */
                    cJSON_SetNumberValue(params_value, ch423_get_open_num_data());                 /* ElectricalOpen_Num */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "SOP2");               /* SOP2 */
                    cJSON_SetNumberValue(params_value, esp_now_get_max30102_data(SOP2));           /* SOP2 */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "HeartRate");          /* HeartRate */
                    cJSON_SetNumberValue(params_value, esp_now_get_max30102_data(HR));             /* HeartRate */
                    io_data = ch423_get_io_data();
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "Living_Light");        /* Living_Light */
                    cJSON_SetNumberValue(params_value, (io_data & 0x01));                           /* Living_Light */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "Living_Fan");          /* Living_Fan */
                    cJSON_SetNumberValue(params_value, ((io_data & 0x02) >> 1));                    /* Living_Fan */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "Living_AirCondition"); /* Living_AirCondition */
                    cJSON_SetNumberValue(params_value, ((io_data & 0x04) >> 2));                    /* Living_AirCondition */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "Living_TV");           /* Living_TV */
                    cJSON_SetNumberValue(params_value, ((io_data & 0x08) >> 3));                    /* Living_TV */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "Living_AirPurifier");  /* Living_AirPurifier */
                    cJSON_SetNumberValue(params_value, ((io_data & 0x10) >> 4));                    /* Living_AirPurifier */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "Bed_Light");           /* Bed_Light */
                    cJSON_SetNumberValue(params_value, ((io_data & 0x20) >> 5));                    /* Bed_Light */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "Bed_Fan");             /* Bed_Fan */
                    cJSON_SetNumberValue(params_value, ((io_data & 0x40) >> 6));                    /* Bed_Fan */
                    params_value = cJSON_GetObjectItemCaseSensitive(params, "Bed_AirCondition");    /* Bed_AirCondition */
                    cJSON_SetNumberValue(params_value, ((io_data & 0x80) >> 7));                    /* Bed_AirCondition */
                    /* update mqtt cjson data end */

                    char *updatedJson = cJSON_PrintUnformatted(root);

                    /* publish mqtt data to service start */
                    ESP_LOGI(TAG, "json data \r\n%s", updatedJson);
                    esp_mqtt_client_publish(client, PublishTopic0, updatedJson, strlen(updatedJson), 0, 0);
                    /* publish mqtt data to service end */

                    cJSON_Delete(root);
                    free(updatedJson);
                }
                xSemaphoreGive(xMQTTSemaphore); /* release mqtt mutex */
            }
        }
        /* publish msg to Aliyun end */

        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}
